import 'dart:developer';

import 'package:flutter/material.dart';

/// 图片安全加载：失败时使用默认图
class SafeLoadImg extends StatefulWidget {
  String url;
  double width;
  double height;
  String defImgPath;

  SafeLoadImg(this.url, this.defImgPath,
      {this.width = 130, this.height = 180, Key? key})
      : super(key: key);

  @override
  _SafeLoadImgState createState() => _SafeLoadImgState();
}

class _SafeLoadImgState extends State<SafeLoadImg> {
  late Image _image;

  @override
  void initState() {
    super.initState();
    var imgUrl = widget.url;
    // log("imgurl: $imgUrl");
    if (imgUrl == null || imgUrl.length == 0) {
      if (widget.defImgPath != null) {
        _image = Image.asset(
          widget.defImgPath,
          width: widget.width,
          height: widget.height,
          fit: BoxFit.cover,
        );
      } else {
        throw Exception("必须设置默认图");
      }
    } else {
      _image = Image.network(
        widget.url,
        width: widget.width,
        height: widget.height,
        fit: BoxFit.fill,
      );
      var resolve = _image.image.resolve(ImageConfiguration.empty);
      resolve.addListener(
          ImageStreamListener((ImageInfo image, bool synchronousCall) {
        // log("图片加载成功");
      }, onError: (Object exception, StackTrace? stackTrace) {
        // log("图片加载失败");
        setState(() {
          // _image = Image.asset("assets/images/img_placeholder.jpeg");
          if (widget.defImgPath != null) {
            _image = Image.asset(
              widget.defImgPath,
              width: widget.width,
              height: widget.height,
              fit: BoxFit.cover,
            );
          } else {
            throw Exception("必须设置默认图");
          }
        });
      }));
    }
  }

  @override
  Widget build(BuildContext context) {
    return _image;
  }
}
